﻿//----------------------------------------------------------------------------------------------------
// The LevelFileInterface is used for saving and laoding of levels
//----------------------------------------------------------------------------------------------------

package HG.TypeInterfaces
{
	import flash.events.*;
	import flash.utils.ByteArray;

	import HG.GameDataTypes.Level;
	import HG.GameDataTypes.NodeInstance;
	
	import HG.Debug;
	
	public class LevelFileInterface extends IFileInterface
	{
		public function LevelFileInterface(fileName:String)
		{
			SetFile(fileName);
		}
		
		//----------------------------------------------------------------------------------------------------
		public function SaveLevel(level:Level)
		{
			var bytes:ByteArray = new ByteArray();
			bytes.writeObject(level);
			Save(bytes);
			
			//Debug.Trace (level.ToString());
		}
		
		//----------------------------------------------------------------------------------------------------
		public function LoadLevel(callback:Function)
		{
			Debug.ASSERT(m_file, "Attempted to load null file");
			
			m_fileReference.browse();
			m_fileReference.addEventListener(Event.SELECT, OnBeginLoad);
			m_fileReference.addEventListener(Event.COMPLETE, OnLoadComplete);
			//m_fileReference.save(bytes, m_file);
			
			m_callback = callback;
		}
		
		//----------------------------------------------------------------------------------------------------
		protected function OnBeginLoad(evt:Event):void 
		{
			m_fileReference.load()
		}
		
		//----------------------------------------------------------------------------------------------------
		protected override function OnLoadComplete(evt:Event):void 
		{
			m_data = m_fileReference.data;
			m_loaded = true;

			var level = new Level();
			var node = new NodeInstance();
			
			level = m_data.readObject() as Level;
			/*node = level.GetNodes()[0];
			
			Debug.Trace(node.ToString());*/

			m_callback(level);
		}
		//----------------------------------------------------------------------------------------------------

	}

}